import os
import ocr
import config
from flask import Flask, request, jsonify


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'D:/资源文件/image'  # 指定上传文件保存目录
app.config['ALLOWED_EXTENSIONS'] = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}  # 允许的文件类型


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify(error='No file part in the request.'), 400

    file = request.files['file']
    if file.filename == '' or not file.file:
        return jsonify(error='No selected file.'), 400

    if file and allowed_file(file.filename):
        filename = file.filename
        ocr.ocr_file_stream(file.stream)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return jsonify(success=True, message=f'File "{filename}" uploaded successfully.')
    else:
        return jsonify(error='Invalid file type.'), 400


# 定义一个处理JSON数据的API接口
@app.route('/ocr/path', methods=['POST'])
def ocr_by_path():
    result = ocr.ocr_by_path(ocr.ocr_path.get('path'))
    return jsonify(result=result)


if __name__ == '__main__':
    app.run(debug=config.configs.get('debug'), host=config.configs.get('host'), port=config.configs.get('port'))
